package plan9

import (
	"fmt"
	"image"
	"os"

	"code.google.com/p/jnj.plan9/draw"
	"code.google.com/p/jnj/graphics"
)

func SetupKeyboardChan(kbd *draw.Keyboardctl) chan rune {
	kchan := make(chan rune)
	go func() {
		for {
			kchan <- <-kbd.C
		}
	}()
	return kchan
}

func SetupMouseChan(mouse *draw.Mousectl) chan *graphics.MouseEvent {
	mchan := make(chan *graphics.MouseEvent)
	go func() {
		for {
			ev := <-mouse.C
			mchan <- &graphics.MouseEvent{
				Point:   image.Point{ev.X, ev.Y},
				Buttons: ev.Buttons,
			}
		}
	}()
	return mchan
}

func SetupClipChan(disp *draw.Display) chan string {
	cchan := make(chan string)
	go func() {
		for {
			snarf := <-cchan
			if snarf == "" {
				s, err := disp.ReadSnarf()
				if err != nil {
					fmt.Fprintln(os.Stderr, err)
				}
				cchan <- string(s)
			} else {
				err := disp.WriteSnarf([]byte(snarf))
				if err != nil {
					fmt.Fprintln(os.Stderr, err)
				}
			}
		}
	}()
	return cchan
}
